package com.wj.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.common.utils.PageUtils;
import com.wj.common.utils.Query;
import com.wj.gulimall.product.dao.CategoryBrandRelationDao;
import com.wj.gulimall.product.dao.CategoryDao;
import com.wj.gulimall.product.entity.CategoryEntity;
import com.wj.gulimall.product.service.CategoryService;
import com.wj.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 返回三级目录
     */
    @Override
    public List<CategoryEntity> listWithTree() {

        List<CategoryEntity> entities = categoryDao.selectList(null);

        for (CategoryEntity entity : entities) {
            if (entity.getParentCid() == 0) {
                toTree(entities, entity);
            }
        }
        List<CategoryEntity> collect = entities.stream().filter(c -> c.getParentCid() == 0)
                .collect(Collectors.toList());

        sortEntities(collect);

        return collect;
    }

    private void sortEntities(List<CategoryEntity> collect) {
        if (collect == null) return;
        collect.sort(Comparator.comparing(CategoryEntity::getSort));
        for (CategoryEntity categoryEntity : collect) {
            sortEntities(categoryEntity.getChildren());
        }
    }

    private void toTree(List<CategoryEntity> entities, CategoryEntity parent) {
        List<CategoryEntity> children = new ArrayList<>();
        for (CategoryEntity entity : entities) {
            if (entity.getParentCid().equals(parent.getCatId())) {
                children.add(entity);
                toTree(entities, entity);
            }
        }
        parent.setChildren(children);
    }


    @Override
    public void removeMenusByIds(List<Long> ids) {
        categoryDao.deleteBatchIds(ids);
    }

    /**
     * 找到完整的路径
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        Collections.reverse(paths);
        return paths.toArray(new Long[0]);
    }

    //同时进行多种缓存操作
    //存储同一个类型下的数据,都可以指定成同一个分区
    @Caching(evict = {
            @CacheEvict(value = {"category"}, key = "'getLevel1Category'"),
            @CacheEvict(value = {"category"}, key = "'getCatalogJson'"),
    })
    // @CacheEvict(value = {"category"},allEntries = true)  //批量删除某个分区下的所有数据
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationDao.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Category() {
        return list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Cacheable(value = "category", key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        List<CategoryEntity> categories = baseMapper.selectList(new QueryWrapper<>());

        List<CategoryEntity> level1Category = categories.stream().filter(c -> c.getParentCid() == 0).collect(Collectors.toList());
        return level1Category.stream()
                .collect(
                        Collectors.toMap(
                                k -> k.getCatId().toString(),
                                v -> {
                                    List<CategoryEntity> categoryEntities = getCategoryEntities(categories, v);
                                    return categoryEntities.stream().map(item -> {
                                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = getCategoryEntities(categories, item).stream()
                                                .map(cat -> new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), cat.getCatId().toString(), cat.getName())).collect(Collectors.toList());
                                        return new Catelog2Vo(v.getCatId().toString(), catelog3Vos, item.getCatId().toString(), item.getName());
                                    }).collect(Collectors.toList());
                                }));
    }

    /**
     * 缓存穿透：空结果缓存
     * 缓存雪崩：设置过期时间
     * 缓存击穿：加锁
     *
     * @return map
     */
    //@Override
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJson");
        Map<String, List<Catelog2Vo>> catalogJson;
        if (StringUtils.isEmpty(catalogJSON)) {
            log.info("缓存不命中");
            catalogJson = getCatalogJsonFromDBWithRedissonLock();
        } else {
            log.info("缓存命中");
            catalogJson = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }
        return catalogJson;
    }

    private Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        //锁的粒度，越细越好
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    private Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();

        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            log.info("获取分布式锁成功");
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
        /*  String lockValue = redisTemplate.opsForValue().get("lock");
            if(uuid.equals(lockValue)){
                redisTemplate.delete("lock");
            }*/
                //lua脚本
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList("lock"), uuid);
            }

            return dataFromDb;
        } else {
            log.info("获取分布式锁失败，等待重试");
            //自旋
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDBWithRedisLock();
        }
    }

    public Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isNotBlank(catalogJSON)) {
            return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }
        log.info("查询数据库");
        List<CategoryEntity> categories = baseMapper.selectList(new QueryWrapper<>());

        List<CategoryEntity> level1Category = categories.stream().filter(c -> c.getParentCid() == 0).collect(Collectors.toList());
        Map<String, List<Catelog2Vo>> catalogJson = level1Category.stream()
                .collect(
                        Collectors.toMap(
                                k -> k.getCatId().toString(),
                                v -> {
                                    List<CategoryEntity> categoryEntities = getCategoryEntities(categories, v);
                                    return categoryEntities.stream().map(item -> {
                                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = getCategoryEntities(categories, item).stream()
                                                .map(cat -> new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), cat.getCatId().toString(), cat.getName())).collect(Collectors.toList());
                                        return new Catelog2Vo(v.getCatId().toString(), catelog3Vos, item.getCatId().toString(), item.getName());
                                    }).collect(Collectors.toList());
                                }));
        String jsonString = JSON.toJSONString(catalogJson);
        redisTemplate.opsForValue().set("catalogJson", jsonString, 1, TimeUnit.HOURS);
        return catalogJson;
    }

    private Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithLocalLock() {
        synchronized (this) {
            return getDataFromDb();
        }
    }

    private List<CategoryEntity> getCategoryEntities(List<CategoryEntity> categories, CategoryEntity v) {
        return categories.stream().filter(c -> c.getParentCid().equals(v.getCatId())).collect(Collectors.toList());
    }

    private void findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
    }
}